import 'package:znmm/UI/utils/my_global.dart';

class CnCartModel {
  int iqty = 0;
  double totalPrice = 0;
  double fSiglePrice = 0;

  //网络字段
  String name = "";
  String itemKey = "";
  int id = 0; //唯一标记
  String title = "";
  String price = "";
  Quantity? quantity;
  Totals? totals;
  String slug = "";
  Meta? meta;
  String backorders = "";
  List<dynamic> cartItemData = [];
  String featuredImage =
      "https://pinshop.com/wp-content/uploads/woocommerce-placeholder-600x600.png";

  CnCartModel({
    this.name = "",
    this.fSiglePrice = 0,
    this.iqty = 0,
    this.totalPrice = 0,
    this.itemKey = "",
    this.id = 0,
    this.title = "",
    this.price = "",
    this.quantity,
    this.totals,
    this.slug = "",
    this.meta,
    this.backorders = "",
    this.cartItemData = const [],
    this.featuredImage =
        "https://pinshop.com/wp-content/uploads/woocommerce-placeholder-600x600.png",
  });

  Map<String, dynamic> toJson() => {
        'name': name,
        'iqty': iqty,
        'databaseId': id,
        'totalPrice': totalPrice,
        'fSiglePrice': fSiglePrice,
      };

  //解析本地数据用
  factory CnCartModel.fromJson(Map<String, dynamic> json) => CnCartModel(
        featuredImage: json['imageStr'] ?? "",
        name: json['name'] ?? "",
        iqty: json['iqty'] ?? 0,
        id: json['databaseId'] ?? 0,
        totalPrice: json['totalPrice'] ?? 0.0,
        fSiglePrice: json['fSiglePrice'] ?? 0.0,
      );
  //解析网络数据
  CnCartModel.fromJson2(Map<String, dynamic> json) {
    itemKey = MyGlobal.checkNullOrEmpty(json['item_key']);
    id = MyGlobal.checkNullOrZero(json['id']);

    name = json['name'] ?? "";
    title = json['title'] ?? "";
    price = json['price'] ?? "";
    quantity = Quantity.fromJson(json['quantity'] ?? {});
    iqty = quantity?.value ?? 0;
    totals = Totals.fromJson(json['totals'] ?? {});
    fSiglePrice = totals?.total ?? 0.0;
    slug = json['slug'] ?? "";
    meta = Meta.fromJson(json['meta'] ?? {});
    backorders = json['backorders'] ?? "";
    cartItemData = json['cart_item_data'] ?? [];
    featuredImage = json['featured_image'] ?? "";

    //totalPrice = fSiglePrice * iqty;
    totalPrice = fSiglePrice;
  }
}

class Quantity {
  int value;
  int minPurchase;
  int maxPurchase;

  Quantity({
    this.value = 0,
    this.minPurchase = 0,
    this.maxPurchase = 0,
  });

  Quantity.fromJson(Map<String, dynamic> json)
      : value = json['value'] ?? 0,
        minPurchase = json['min_purchase'] ?? 0,
        maxPurchase = json['max_purchase'] ?? 0;
}

class Totals {
  String subtotal;
  double subtotalTax;
  double total;
  double tax;

  Totals({
    this.subtotal = "",
    this.subtotalTax = 0,
    this.total = 0,
    this.tax = 0,
  });

  Totals.fromJson(Map<String, dynamic> json)
      : subtotal = json['subtotal'] ?? "",
        subtotalTax = json['subtotal_tax']?.toDouble() ?? 0.0,
        total = json['total']?.toDouble() ?? 0.0,
        tax = json['tax']?.toDouble() ?? 0.0;
}

class Meta {
  String productType;
  String sku;
  Dimensions? dimensions;
  double weight;
  Map<String, String> variation;

  Meta({
    this.productType = "",
    this.sku = "",
    this.dimensions,
    this.weight = 0,
    this.variation = const {},
  });

  Meta.fromJson(Map<String, dynamic> json)
      : productType = json['product_type'] ?? "",
        sku = json['sku'] ?? "",
        dimensions = Dimensions.fromJson(json['dimensions'] ?? {}),
        weight = json['weight']?.toDouble() ?? 0.0,
        variation = _parseVariation(json['variation'] ?? {});

  static Map<String, String> _parseVariation(dynamic variation) {
    if (variation is Map) {
      // 如果是 Map，直接转换
      return Map<String, String>.from(variation);
    } else if (variation is List) {
      // 如果是 List，将其转换成 Map（假设每个元素是有 key 和 value 的 Map）
      return {
        for (var item in variation)
          if (item['key'] != null && item['value'] != null)
            item['key'].toString(): item['value'].toString()
      };
    } else {
      // 如果既不是 Map 也不是 List，则返回空 Map
      return {};
    }
  }
}

class Dimensions {
  String length;
  String width;
  String height;
  String unit;

  Dimensions({
    this.length = "",
    this.width = "",
    this.height = "",
    this.unit = "",
  });

  Dimensions.fromJson(Map<String, dynamic> json)
      : length = json['length'] ?? "",
        width = json['width'] ?? "",
        height = json['height'] ?? "",
        unit = json['unit'] ?? "";
}
